import { Point } from './point';

export class Rect {
    /**矩形x坐标 */
    public x: number;
    /**矩形y坐标 */
    public y: number;
    /**矩形宽度 */
    public width: number;
    /**矩形高度 */
    public height: number;
    /**
     * 构造哈桑农户
     * @param x 矩形x坐标
     * @param y 矩形y坐标
     * @param width 矩形宽度
     * @param height 矩形高度
     */
    constructor(x: number = NaN, y: number = NaN, width: number = 0, height: number = 0) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    /**
     * 判断是否为空矩形
     */
    public isEmpty(): boolean {
        if (this.x === NaN || this.y === NaN || this.width === 0 || this.height === 0) {
            return true;
        }
        return false;
    }
    /**
     * 计算当前矩形与传入矩形的并集，并返回一个新的矩形
     * @param rect 
     */
    public union(rect: Rect) {
        return Rect.union(this, rect);
    }
    /**
     * 判断当前矩形与传入矩形是否相交
     * @param rect 
     */
    public isIntersect(rect: Rect) {
        if (this.isEmpty()) {
            return Rect.Empty;
        }
        return Rect.isIntersect(this, rect);
    }
    /**
     * 判断点是否落在线条渲染区域内
     * @param point 
     */
    public pointInRect(point: Point): boolean {
        if (point.x >= this.x && point.x <= this.x + this.width
            && point.y >= this.y && point.y <= this.y + this.height) {
                return true;
        }
        return false;
    }
    /**
     * 计算两个矩形的并集，并返回一个新的矩形
     * @param rect1 
     * @param rect2 
     */
    public static union(rect1: Rect, rect2: Rect) {
        if (rect1.isEmpty()) {
            return rect2;
        }
        if (rect2.isEmpty()) {
            return rect1;
        }
        const minX = Math.min(rect1.x, rect2.x);
        const minY = Math.min(rect1.y, rect2.y);
        const maxX = Math.max(rect1.x + rect1.width, rect2.x + rect2.width);
        const maxY = Math.max(rect1.y + rect1.height, rect2.y + rect2.height);
        return new Rect(minX, minY, maxX - minX, maxY - minY);
    }
    /**
     * 判断两个矩形是否相交
     * @param rect1 
     * @param rect2 
     */
    public static isIntersect(rect1: Rect, rect2: Rect): boolean {
        const minX = Math.min(rect1.x, rect2.x);
        const minY = Math.min(rect1.y, rect2.y);
        const maxX = Math.max(rect1.x + rect1.width, rect2.x + rect2.width);
        const maxY = Math.max(rect1.y + rect1.height, rect2.y + rect2.height);
        if (maxX - minX <= rect1.width + rect2.width && maxY - minY <= rect1.height + rect2.height) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 获取一个空矩形
     */
    public static get Empty() {
        return new Rect();
    }
}